﻿using KTWpm.Management.Api.Infrastructure;
using KTWpm.Management.Domain;

namespace KTWpm.Management.Api.Application;

public class SetWeightCommandHandle : ICommandHandle<SetWeightCommand>
{
    private readonly ManagementDbContext _dbContext;
    private readonly IBreadService _breadService;

    public SetWeightCommandHandle(ManagementDbContext dbContext, IBreadService breadService)
    {
        _dbContext = dbContext;
        _breadService = breadService;

        DomainEvents.PetWeightUpdated.Subscribe((domainEvent) =>
        {
            // Send a message
        });
    }

    public async Task Handle(SetWeightCommand command)
    {
        var pet = await _dbContext.Pets.FindAsync(command.Id);
        if (pet == null)
        {
            throw new ArgumentException("Pet not found.");
        }
        pet.SetWeight(command.Weight, _breadService);
        await _dbContext.SaveChangesAsync();
    }
}
